<template>
  <common-list-group>
    <common-tree
      slot="group"
      :is-request="isRequest"
      :treeData="deptSelect"
      :treeProp="treeProp"
      :searchPlaceholder="'查询组织'"
      isSlot
      :treeLoading="treeLoading"
      :current-node-key="currentNodeKey"
      @handleNodeClick="handleNodeClick"
    >
      <div
        style="width: 100%"
        slot-scope="{ scope }"
        :class="{ 'e-t-content': !scope.data.freeze }"
      >
        <common-carousel-text :content="scope.data.label" :font-size="14">
        </common-carousel-text>
      </div>
    </common-tree>

    <!-- 头部搜素start -->
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        @submit.native.prevent
        :model="query"
        ref="queryForm"
        :inline="true"
        label-width="50px"
      >
        <el-form-item label="用户名" prop="userName">
          <common-input @enter="handleQuery" v-model="query.userName" />
        </el-form-item>

        <el-form-item label="姓名" prop="nickName">
          <common-input v-model="query.nickName" @enter="handleQuery" />
        </el-form-item>

        <el-form-item label="手机号" prop="phonenumber">
          <common-input v-model="query.phonenumber" @enter="handleQuery" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <common-input v-model="query.email" @enter="handleQuery" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="query.status">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="正常" :value="0"></el-option>
            <el-option label="冻结" :value="1"></el-option>
            <el-option label="锁定" :value="2"></el-option>
            <el-option label="注销" :value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </common-search>
    <!-- 头部搜素end -->

    <!-- 按钮start -->
    <el-row slot="tools" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="edit(null)"
          data-test="user-add"
          v-hasPermi="['system:user:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          @click="importShow"
          v-hasPermi="['system:user:import']"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5" v-hasPermi="['system:user:updateStatus']">
        <el-dropdown @command="changeUserStatus" style="width: 100px">
          <el-button plain style="width: 100px" class="btn-color-hover">
            设置状态<commonIcon
              iconName="el-icon-arrow-down el-icon--right"
              iconType="icon"
              :iconSize="12"
            ></commonIcon>
          </el-button>
          <el-dropdown-menu slot="dropdown" style="width: 100px">
            <el-dropdown-item command="0">正常</el-dropdown-item>
            <el-dropdown-item command="1">冻结</el-dropdown-item>
            <el-dropdown-item command="2">锁定</el-dropdown-item>
            <el-dropdown-item command="3">注销</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['system:user:batchUpdateSecondPolicy']">
        <el-dropdown @command="changeLoginPolicy" style="width: 120px">
          <el-button plain style="width: 120px" class="btn-color-hover">
            设置辅助策略<commonIcon
              iconName="el-icon-arrow-down el-icon--right"
              iconType="icon"
              :iconSize="12"
            ></commonIcon>
          </el-button>
          <el-dropdown-menu slot="dropdown" style="width: 120px">
            <el-dropdown-item
              v-for="item of loginPolicySelect"
              :key="item.policyType"
              :command="item.policyType"
            >
              {{ item.policyName }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['system:user:resetPwd']">
        <el-dropdown @command="changeUserPwd" style="width: 100px">
          <el-button plain style="width: 100px" class="btn-color-hover">
            重置密码<commonIcon
              iconName="el-icon-arrow-down el-icon--right"
              iconType="icon"
              :iconSize="12"
            ></commonIcon>
          </el-button>
          <el-dropdown-menu slot="dropdown" style="width: 100px">
            <el-dropdown-item command="1">默认密码</el-dropdown-item>
            <el-dropdown-item command="2">随机密码</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
      <!-- <el-col :span="1.5">
      <el-button type="danger" plain icon="el-icon-delete" :disabled="multiple" @click="del(selectionIds)" hasPermi>批量删除</el-button>
      </el-col>-->
    </el-row>
    <!-- 按钮end -->

    <!--列表 start-->
    <common-table
      slot="content"
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户名" align="left" prop="userName" />
      <el-table-column
        label="姓名"
        align="left"
        prop="nickName"
        show-overflow-tooltip
      />
      <el-table-column label="手机号" align="left" prop="phone" width="120" />
      <!--      <el-table-column label="邮箱" align="left" prop="decodeEmail" show-overflow-tooltip/>-->
      <!--<el-table-column label="用户来源" align="left" prop="userSource">
        <template slot-scope="{row}">
          <span v-if="row.userSource == 1">自建用户</span>
          <span v-else-if="row.userSource == 2">从外系统同步</span>
        </template>
      </el-table-column>-->

      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="{ row }">
          <el-tag type="success" v-if="row.status == 0">正常</el-tag>
          <el-tag type="danger" v-else-if="row.status == 1">冻结</el-tag>
          <el-tag type="danger" v-else-if="row.status == 2">锁定</el-tag>
          <el-tag type="danger" v-else>注销</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="left"
        prop="createTime"
        width="170"
      />
      <el-table-column
        label="操作"
        align="left"
        :width="configItem.IS_SYNC_USER ? '210' : '90'"
      >
        <template slot-scope="{ row }">
          <el-button type="text" @click="detail(row)">详情</el-button>
          <el-button
            v-if="row.status != 3"
            type="text"
            @click="edit(row)"
            v-hasPermi="['system:user:edit']"
            >编辑</el-button
          >
          <el-button
            v-if="row.status != 3 && configItem.IS_SYNC_USER"
            type="text"
            @click="synchronizeUser(row)"
            >同步用户</el-button
          >
          <el-button
            v-if="row.status != 3 && configItem.IS_SYNC_USER"
            type="text"
            @click="updateUser(row)"
            >更新用户</el-button
          >
        </template>
      </el-table-column>
    </common-table>

    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="query.pageNum"
      :limit.sync="query.pageSize"
      @pagination="getList"
    />

    <editDialog
      ref="editDialog"
      :deptSelect="deptSelect"
      :roleSelect="roleSelect"
      :loginPolicySelect="loginPolicySelect"
      :expDuration="userDuration"
      :authSelect="authSelect"
      @refresh="getList"
    />
    <userDetail
      ref="userDetail"
      :loginPolicySelect="loginPolicySelect"
      :authSelect="authSelect"
    />
    <common-upload-dialog
      download-path="system/downFileByemplateName"
      upload-path="/system/user/importData"
      template-name="userTemplate.xls"
      report-path="system/downErrorReportByemplateName"
      ref="uploadDialog"
      :getList="getList"
    />
  </common-list-group>
</template>

<script>
import editDialog from "./components/userAdd";
import userDetail from "./components/userDetail";
import {
  user_status,
  user_pwd,
  user_list,
  dept_select,
  role_select,
  auth_select,
  loginpolicy_select,
  user_duration,
  batchUpdateSecondPolicy,
  synchronizeUser,
} from "@/api/management/usercenter/user.js";
import { decode, encode } from "@/utils/aesUtils";
import Utils from "@/utils";
import BaseList from "@/mixins/BaseList";
import { mapGetters } from "vuex";
import CommonIcon from "@/components/CommonIcon";

export default {
  components: { editDialog, userDetail, CommonIcon },
  mixins: [BaseList],
  props: {},
  data() {
    return {
      isRequest: false,
      treeLoading: false,
      filterMenu: "", //菜单筛选
      deptSelect: [], // 菜单树
      treeProp: {
        // 树参数
        children: "children",
        label: "label",
        disabled: false,
      },
      showSearch: true, // 查询部分显示
      total: 1, // 总条数
      loading: false, // table 加载中
      list: [], // 数据列
      selectionIds: "", // 列表选中数据id
      chooseSelection: [],
      single: true, // 非单个禁用
      multiple: true, // 非多个禁用
      query: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        nickName: null,
        status: null,
        email: null,
        phonenumber: null,
        deptId: null,
      }, // 查询条件
      deptselect: [],
      roleSelect: [],
      authSelect: [],
      loginPolicySelect: [],
      userDuration: 0,
      editUserStatus: "",
      editUserPwd: "",
      currentNodeKey: "",
      configItem: sp_config,
    };
  },
  watch: {
    filterMenu(val) {
      this.$refs.deptSelect.filter(val);
    },
  },

  methods: {
    importShow() {
      this.$refs.uploadDialog.show();
    },
    handleNodeClick(data) {
      if (!!data.data.freeze) {
        this.query.deptId = data.data.id;
        this.getList();
      }
    },
    changeUserStatus(data) {
      this.editUserStatus = data;
      if (!!this.selectionIds && this.selectionIds.length > 0) {
        let hasZhuxiao = false;
        this.chooseSelection.map((v) => {
          if (v.status == 3) {
            hasZhuxiao = true;
          }
        });
        if (hasZhuxiao) {
          return this.$GlobalErrorConfirm(
            "操作失败",
            "所选项中有已注销用户，不可设置状态"
          );
        }
        //批量删除
        this.$GlobalDeleteConfirm("是否确认编辑数据项？")
          .then(() => {
            let ids = this.selectionIds.join(",");
            user_status({ status: data, ids: ids }).then((res) => {
              if (res && res.code === 200) {
                this.$GlobalSuccessMessage("操作成功");
                this.getList();
                this.editUserStatus = null;
              } else {
                this.$GlobalErrorConfirm("操作失败", res.msg).then();
              }
            });
          })
          .catch(() => {});
      } else {
        this.$GlobalErrorConfirm("操作失败", "请选择用户");
        this.editUserStatus = null;
      }
    },
    changeUserPwd(data) {
      this.editUserPwd = data;
      if (!!this.selectionIds && this.selectionIds.length > 0) {
        let hasZhuxiao = false;
        this.chooseSelection.map((v) => {
          if (v.status == 3) {
            hasZhuxiao = true;
          }
        });
        if (hasZhuxiao) {
          return this.$GlobalErrorConfirm(
            "操作失败",
            "所选项中有已注销用户，不可重置密码"
          );
        }
        //批量删除

        this.$GlobalDeleteConfirm("是否确认编辑数据项？")
          .then(() => {
            let ids = this.selectionIds.join(",");
            user_pwd({ genPwdWay: data, ids: ids }).then((res) => {
              if (res && res.code === 200) {
                this.$GlobalSuccessMessage("操作成功");
                this.getList();
                this.editUserPwd = null;
              } else {
                this.$GlobalErrorConfirm("操作失败", res.msg).then();
              }
            });
          })
          .catch(() => {});
      } else {
        this.$GlobalErrorConfirm("操作失败", "请选择用户");
        this.editUserPwd = null;
      }
    },
    /**
     * 过滤
     */
    filterNode(value, data, node) {
      // 如果什么都没填就直接返回
      if (!value) return true;
      // 如果传入的value和data中的label相同说明是匹配到了
      if (data.label.indexOf(value) !== -1) {
        return true;
      }
      // 否则要去判断它是不是选中节点的子节点
      return this.checkBelongToChooseNode(value, data, node);
    },

    // 判断传入的节点是不是选中节点的子节点
    checkBelongToChooseNode(value, data, node) {
      const level = node.level;
      // 如果传入的节点本身就是一级节点就不用校验了
      if (level === 1) {
        return false;
      }
      // 先取当前节点的父节点
      let parentData = node.parent;
      // 遍历当前节点的父节点
      let index = 0;
      while (index < level - 1) {
        // 如果匹配到直接返回
        if (parentData.data.label.indexOf(value) !== -1) {
          return true;
        }
        // 否则的话再往上一层做匹配
        parentData = parentData.parent;
        index++;
      }
      // 没匹配到返回false
      return false;
    },
    /**
     * 选择
     */
    handleSelectionChange(selection) {
      this.selectionIds = selection.map((item) => item.userId);
      this.chooseSelection = selection;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /**
     * 获取列表
     */
    getList() {
      this.loading = true;
      this.isRequest = true;
      let query = { ...this.query };
      if (query.email) query.email = encode(query.email);
      if (query.phonenumber) query.phonenumber = encode(query.phonenumber);
      user_list(query)
        .then((res) => {
          if (res && res.code === 200) {
            this.list = res.rows.reduce((r, c) => {
              r.push({
                ...c,
                phone: Utils.phoneEncryption(decode(c.phonenumber)),
                decodeEmail: Utils.emailEncryption(decode(c.email)),
              });
              return r;
            }, []);
            this.total = res.total;
          } else {
            this.list = [];
            this.total = 0;
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.loading = false;
          this.isRequest = false;
        });
    },

    handlePhoneNumber(phoneNumber) {
      return (
        phoneNumber.substr(0, 3) +
        "****" +
        phoneNumber.substr(phoneNumber.length - 4, phoneNumber.length - 1)
      );
    },

    //组织下拉选择
    getDeptSelect() {
      this.treeLoading = true;
      dept_select({})
        .then((res) => {
          if (res && res.code === 200) {
            this.deptSelect = res.data;
            this.currentNodeKey = res.data.length ? res.data[0].id : "";
            this.query.deptId = res.data.length ? res.data[0].id : "";
          } else {
            this.deptSelect = [];
            // this.$GlobalErrorConfirm('获取组织列表失败', res.msg, '重新加载').then(() => {
            //   this.getDeptSelect()
            // })
          }
        })
        .finally(() => {
          this.treeLoading = false;
        });
    },
    //角色下拉选择
    getRoleSelect() {
      role_select({}).then((res) => {
        if (res && res.code === 200) {
          this.roleSelect = res.data;
        } else {
          this.roleSelect = [];
          // this.$GlobalErrorConfirm('获取角色列表失败', res.msg, '重新加载').then(() => {
          //   this.getRoleSelect()
          // })
        }
      });
    },
    //数据权限下拉选择
    getAuthSelect() {
      auth_select({}).then((res) => {
        if (res && res.code === 200) {
          this.authSelect = res.data;
        } else {
          this.authSelect = [];
          // this.$GlobalErrorConfirm('获取权限列表失败', res.msg, '重新加载').then(() => {
          //   this.getAuthSelect()
          // })
        }
      });
    },
    //登录辅助下拉选择
    getPolicySelect() {
      loginpolicy_select({}).then((res) => {
        if (res && res.code === 200) {
          this.loginPolicySelect = res.data;
        } else {
          this.loginPolicySelect = [];
          // this.$GlobalErrorConfirm('获取辅助策略列表失败', res.msg, '重新加载').then(() => {
          //   this.getPolicySelect()
          // })
        }
      });
    },
    //用户有效期
    // getDurationSelect() {
    //   user_duration({})
    //     .then((res) => {
    //       if (res && res.code === 200) {
    //         this.userDuration = res.msg;
    //       } else {
    //         // this.$GlobalErrorConfirm('获取用户有效期列表失败', res.msg, '重新加载').then(() => {
    //         //   this.getDurationSelect()
    //         // })
    //       }
    //     })
    //     .catch((err) => {
    //       // this.$GlobalErrorConfirm('获取用户有效期列表失败', err.msg, '重新加载').then(() => {
    //       //   this.getDurationSelect()
    //       // })
    //     });
    // },
    /**
     * 查询
     */
    handleQuery() {
      this.query.pageNum = 1;
      this.getList();
    },
    /**
     * 重置查询
     */
    resetQuery() {
      this.query = this.$options.data().query;
    },

    synchronizeUser(row) {
      this.$GlobalDeleteConfirm("是否确认同步用户")
        .then(() => {
          synchronizeUser({ modifyMode: "add", userName: row.userName }).then(
            (res) => {
              if (res && res.code === 200) {
                this.getList();
                this.$GlobalSuccessMessage(res.msg);
              } else {
                this.$GlobalErrorConfirm("同步失败", res.msg);
              }
            }
          );
        })
        .catch(() => {});
    },

    updateUser(row) {
      this.$GlobalDeleteConfirm("是否确认更新用户")
        .then(() => {
          synchronizeUser({
            modifyMode: "change",
            userName: row.userName,
          }).then((res) => {
            if (res && res.code === 200) {
              this.getList();
              this.$GlobalSuccessMessage(res.msg);
            } else {
              this.$GlobalErrorConfirm("更新失败", res.msg);
            }
          });
        })
        .catch(() => {});
    },

    /**
     * 添加/编辑
     */
    edit(row) {
      this.$refs.editDialog.show(
        row
          ? { ...row }
          : { deptId: this.query.deptId ? this.query.deptId : [] }
      );
    },
    /**
     * 详情
     */
    detail(row) {
      this.$refs.userDetail.show(row ? { ...row } : {});
    },
    /**
     * 修改辅助策略
     */
    changeLoginPolicy(val) {
      if (!!val && this.selectionIds.length > 0) {
        let hasZhuxiao = false;
        this.chooseSelection.map((v) => {
          if (v.status == 3) {
            hasZhuxiao = true;
          }
        });
        if (hasZhuxiao) {
          return this.$GlobalErrorConfirm(
            "操作失败",
            "所选项中有已注销用户，不可设置辅助策略"
          );
        }
        //批量删除
        this.$GlobalDeleteConfirm("是否确认编辑数据项？")
          .then(() => {
            let ids = this.selectionIds.join(",");
            batchUpdateSecondPolicy({ policy: val, ids: ids }).then((res) => {
              if (res && res.code === 200) {
                this.$GlobalSuccessMessage("操作成功");
                this.getList();
              } else {
                this.$GlobalErrorConfirm("操作失败", res.msg).then();
              }
            });
          })
          .catch(() => {});
      } else {
        this.$GlobalErrorConfirm("操作失败", "请选择用户");
      }
    },
  },
  created() {
    this.getList();
    this.getDeptSelect();
    this.getRoleSelect();
    this.getAuthSelect();
    this.getPolicySelect();
    // this.getDurationSelect();
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-tree {
  font-size: 14px;

  .e-t-content {
    width: 100%;
    &:hover {
      cursor: not-allowed;
    }
  }
}

.tree-data-wrap {
  margin-top: 8px;
  max-height: calc(100% - 40px);
  overflow-y: scroll;
}
</style>
